﻿using System;
using System.Text;
using System.Diagnostics;

using Builderator.Core.Plugin;
using Builderator.Core.Interfaces;

namespace Builderator.Core.Action
{
    public class NAntPlugin : PluginBase, ICompile
    {
        [DocumentProperty("Executable", typeof(Uri), false, DocumentProperty.BrowseUriType.File, "*.exe|*.exe")]
        public string Executable
        {
            get;
            set;
        }

        [DocumentProperty("Build", typeof(Uri), false, DocumentProperty.BrowseUriType.File, "*.*|*.*")]
        public string Build
        {
            get;
            set;
        }

        [DocumentProperty("Properties", typeof(VariableDictionary), false)]
        public VariableDictionary Properties
        {
            get;
            set;
        }

        public NAntPlugin()
            : base("NAnt", new Guid("F25224E2-F455-11E0-A871-68204924019B"))
        {
            this.Properties = new VariableDictionary();

            this.Properties.Add(new Variable("OutputPath", VariableType.Path, "{BuildPath}\\Build", true));
        }

        public override ExecutionResult Run()
        {
            StringBuilder builder = new StringBuilder();
            Process process = new Process();

            builder.AppendFormat("-buildfile:{0}", this.Build);

            foreach (Variable property in this.Properties)
            {
                if (property.Value.Contains("{") && property.Value.Contains("}"))
                {
                    string name;
                    int index1, index2;
                    Variable variable;

                    index1 = property.Value.IndexOf("{");

                    index2 = property.Value.IndexOf("}");

                    name = property.Value.Substring(index1 + 1, index2 - 1);

                    variable = this.Variables.Find(name);

                    property.Value = property.Value.Replace("{" + name + "}", variable.Value);
                }

                builder.AppendFormat(" -D:{0}={1}", property.Name, property.Value);
            }

            builder.Append(" build");

            this.DebugMessage(builder.ToString());

            process.StartInfo.Arguments = builder.ToString();
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.FileName = this.Executable;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.UseShellExecute = false;
            
            process.EnableRaisingEvents = true;
            process.Exited += new EventHandler(process_Exited);

            process.Start();

            this.DebugMessage(process.StandardOutput);

            return base.Run();
        }

        private void process_Exited(object sender, EventArgs e)
        {
            this.Running = false;

            this.ExitCode = ((Process)sender).ExitCode;
        }
    }
}